from google.appengine.ext import webapp
from web.constants import get_admin_user, title, slogan, search, menu, ARTICLES_ON_PAGE, \
    donate
from appengine_utilities import sessions
from web.models import ArticleModel, CommentModel, CommonStatisticModel
from google.appengine.ext.webapp import template
import uuid
import os
from web.translate import translate
from web.utils import tilte_translate
from web.stats import get_stat_string

class ViewArticle(webapp.RequestHandler):
    def get(self, u_id, lang="rus"):
        user = get_admin_user() 
#        u_id = self.request.get('uuid')
        #lang = self.request.get('lang')
        
        session = sessions.Session()
        if not session.has_key('user_id'):
            session['user_id'] = uuid.uuid4().hex        
        
        try:
            article = ArticleModel.get_by_id(int(u_id))
        except:
            self.redirect("/page_404")
            return None
        
        if not article:
            self.redirect("/page_404")
            return None
        
        comments = article.commentmodel_set
        comments.fetch(100)
        
        all = self.request.get('all')
        if all:
            comments = CommentModel.all()
        comments.order('-date')
        
         
        template_values = {
        'statistics': get_stat_string(),
        'session':session,
        'comments':comments,
        'title':title,
        'slogan':slogan,
        'donate':donate,
        'search':search,
        'lang':lang,
        'id':u_id,
        'article': article,
        'user': user,
        'menu':menu,
        "name" : self.request.get('name'),
        "site" : self.request.get('site'),
        "comment" : self.request.get('comment')        
        }
        path = os.path.join(os.path.dirname(__file__), 'view_article.html')
        self.response.out.write(template.render(path, template_values))

class TemplatePage(webapp.RequestHandler):
    def get_render_page(self, category="news", lang="rus", index=0, stat_string=None):
        
        stats = None
        
        if category == "statistics":
            stats = CommonStatisticModel().all()
            stats.order("-date")
            stats.fetch(30)
                        
            template_values = {
            'stats': stats,
            'stat_string':stat_string
            }
                    
        if int(index) <= 0:
            index = 0
        
        find = False
        for menu_item in menu:
            if category == menu_item['id']:
                find = True
                break;
        
        if not find:
            self.redirect("/page_404")
        
        query = ArticleModel.all()
        
        if category != "other":       
            query.filter("category", category)
        
        query.order('-date')
        
        articles = query.fetch(ARTICLES_ON_PAGE, ARTICLES_ON_PAGE * int(index))
        
        user = get_admin_user()
        
        template_values = {
        'stats': stats,
        'stat_string':stat_string,
        'lang': lang,
        'index': int(index) + 1,
        'index1': int(index) - 1,
        'user': user,
        'category':category,
        'articles': articles,
        }
        
        path = os.path.join(os.path.dirname(__file__), 'article_list.html')
        return template.render(path, template_values)
        
    def get(self, category="news", lang="rus", index=0):
        
        user = get_admin_user()
        if user:
            username = "Hello " + user.nickname()
        else:
            username = "Hello anonimous"
        
        #category = self.request.get("page")
        if not category:
            category = "news"
        
        #lang = self.request.get('lang')
        
        stat_string = get_stat_string()
              
        content = self.get_render_page(category, lang, index, stat_string)
        
        template_values = {
        'statistics': stat_string,
         'title': title,
         'slogan': slogan,
         'donate':donate,
         'search': search,
         'lang': lang,
         'user': user,
         'page':category,
         'menu' : menu,
        'content': content,
        'username':username      
        }
        path = os.path.join(os.path.dirname(__file__), 'template.html')
        self.response.out.write(template.render(path, template_values))  

class CreateUpdateArticle(webapp.RequestHandler):
    def get(self):
        delete = self.request.get('delete')
        if delete:
            uuid = self.request.get('uuid')
            model = ArticleModel.get_by_id(int(uuid))
            if model:
                model.delete()
                self.redirect("/")
                return True
        
        self.post()
    
    def post(self):        
        uuid = self.request.get('uuid')
        category = self.request.get('category')
        if uuid:
            model = ArticleModel.get_by_id(int(uuid))
        else:
            model = ArticleModel()
            
        user = get_admin_user()
        if user:
            model.author = user
        
        
        if self.request.get('create'):
            model.title = self.request.get('title')
            model.title_eng = translate(model.title, src="ru", to="en")
            model.content = self.request.get('content')
            model.content_eng = translate(model.content, src="ru", to="en")
            model.category = self.request.get('category')
            model.keywords = self.request.get('keywords')
            model.visible = self.request.get('visible')
            
            model.title_translit = tilte_translate(model.title)
            model.put()
            uuid = model.key().id() 
        
        
        template_values = {
        'user': user,
        'menu':menu,
        'category': category,
        'uuid': uuid,
        'model': model,
        }
        
        path = os.path.join(os.path.dirname(__file__), 'edit_article.html')
        self.response.out.write(template.render(path, template_values))
